import React, { Component } from 'react';
import { connect } from 'react-redux';
import AdvancedQuery from './Components/AdvancedQuery';
import AdvancedRelationQuery from './Components/AdvancedRelationQuery';
import dataCenter from './dataCenter';
import {
	Input,
	Collapse,
	Button,
	Row,
	Col,
	Icon,
	Form,
	Select,
	InputNumber
} from 'antd';

import * as d3 from 'd3';

const FormItem = Form.Item;
const Option = Select.Option;
const OptGroup = Select.OptGroup;

import {
	updateData,
	demo1,
	demo2,
	getAllNodesCount,
	demo5,
	demo6,
	getDirectedRelationByNodeId,
	searchRelations,
	getAllRelationshipsCount,
	advancedQueryNodes,
	getPaths,
	advancedQueryPath,
	getAllRelationTypes,
	advancedQueryRelationships
} from './action';


const Panel = Collapse.Panel;

class SearchBar extends Component {
	componentDidMount() {
		this.props.dispatch(getAllNodesCount());
		this.props.dispatch(getAllRelationshipsCount());
		dataCenter.getLabels().then(labels => {
			this.setState({
				labels
			})
		});
		dataCenter.getPropertyKeys().then(propertyKeys => {
			this.setState({
				propertyKeys
			})
		})
		dataCenter.getAllRelationTypes().then(relationTypes => {
			this.setState({
				relationTypes
			})
		})
		this.init();
	}
	state = {
		directionComType: 'out',
		labels: [],
		propertyKeys: [],
		relationTypes: [],
		minLength: null,
		maxLength: null
	}
	init() {
		// this.searchBar = d3.select(this.refs.searchBar);
		
		// this.searchBar.call(this.editerDrag)

		// this.editerDrag = d3.drag()
		// 	.clickDistance(100)
		// 	.on('drag', function(d) {
		// 		d.left += d3.event.dx;
		// 		d.top += d3.event.dy;
		// 		d3.select(this)
		// 			.style('left', d => `${d.left}px`)
		// 			.style('top', d => `${d.top}px`)
		// 	});
	}
	handleChange = (type, value) => {
		this.setState({
			[type]: value
		})
	}
	search = () => {
		this.props.setSearchType('node');
		if (this.refs.searchValue.refs.input.value) 
		this.props.dispatch(updateData(this.refs.searchValue.refs.input.value));
	}
	demo1() {
		this.props.setSearchType('');
		this.props.dispatch(demo1());
	}

	demo2 = () => {
		this.props.setSearchType('');
		this.props.dispatch(demo2());
	}

	getAllNodesCount = () => {
		this.props.setSearchType('');
		this.props.dispatch(getAllNodesCount());
	}

	demo5 = (nodeId) => {
		this.props.setSearchType('');
		if (this.refs.searchNodeByNodeId.refs.input.value) 
		this.props.dispatch(demo5(this.refs.searchNodeByNodeId.refs.input.value));
	}

	demo6 = (nodeId) => {
		this.props.setSearchType('');
		this.props.dispatch(demo5(this.refs.searchRelationshipsByNodeId.refs.input.value));
		this.props.dispatch(demo6(this.refs.searchRelationshipsByNodeId.refs.input.value));
	}

	getDirectedRelationByNodeId = () => {
		const startNodeId = this.refs.startNodeId.refs.input.value;
		// const endNodeId = this.refs.endNodeId.refs.input.value;
		if (startNodeId)
		this.props.dispatch(getDirectedRelationByNodeId(startNodeId, this.state.directionComType));
	}

	searchRelations = () => {
		this.props.setSearchType('node');
		if (this.refs.relationSearch.refs.input.value)
		this.props.dispatch(searchRelations(this.refs.relationSearch.refs.input.value));
	}

	searchDetailNode = (searchData) => {
		const staticParams = {q: searchData.q, labels: searchData.labels};
		const dealedSearchData = _.cloneDeep(searchData);
		delete dealedSearchData.q;
		delete dealedSearchData.labels;
		const props = Object.keys(dealedSearchData).reduce((pre, key, index) => {
			if (dealedSearchData[key]) {
				return [...pre, [key, dealedSearchData[key]]]
			} else {
				return pre;
			}
		}, []);
		let dealedParams = {...staticParams, props, graph: true, limit: 20};
		const finalParams = props.length ? dealedParams : {...staticParams, graph: true, limit: 20};
		if (finalParams.q) {
			this.props.setSearchType('node');
			this.props.dispatch(advancedQueryNodes(finalParams));
		}
	}

	advancedQueryRelationships = (searchData) => {
		const staticParams = {q: searchData.q, labels: searchData.labels, type: searchData.type};
		const dealedSearchData = _.cloneDeep(searchData);
		delete dealedSearchData.q;
		delete dealedSearchData.labels;
		delete dealedSearchData.type;
		const props = Object.keys(dealedSearchData).reduce((pre, key, index) => {
			if (dealedSearchData[key]) {
				return [...pre, [key, dealedSearchData[key]]]
			} else {
				return pre;
			}
		}, []);
		let dealedParams = {...staticParams, props, graph: true, limit: 20};
		const finalParams = props.length ? dealedParams : {...staticParams, graph: true, limit: 20};
		if (finalParams.q)
		this.props.dispatch(advancedQueryRelationships(finalParams));
	}

	getPaths = () => {
		const { directionComType } = this.state;
		let direction;
		if (directionComType === 'out') {
			direction = 0;
		} else if (directionComType === 'in') {
			direction = 1;
		} else {
			direction = 2;
		}
		const start = this.refs.start.refs.input.value;
		const destination = this.refs.destination.refs.input.value;
		const minLength = this.state.minLength;
		const maxLength = this.state.maxLength;
		const params = {start, destination, minLength, maxLength};
		const finalParams = Object.keys(params).reduce((pre, item) => {
			if (params[item]) {
				return Object.assign(pre, {[item]: params[item]})
			} else {
				return pre;
			}
		}, {direction})
		if (finalParams.start)
		this.props.dispatch(getPaths(finalParams));
	}

	advancedQueryPath = () => {
		const { directionComType } = this.state;
		let direction;
		if (directionComType === 'out') {
			direction = 0;
		} else if (directionComType === 'in') {
			direction = 1;
		} else {
			direction = 2;
		}
		const start = this.refs.start.refs.input.value;
		const destination = this.refs.destination.refs.input.value;
		const minLength = this.state.minLength;
		const maxLength = this.state.maxLength;
		const params = {start, destination, minLength, maxLength};
		const finalParams = Object.keys(params).reduce((pre, item) => {
			if (params[item]) {
				return Object.assign(pre, {[item]: params[item]})
			} else {
				return pre;
			}
		}, {direction})
		if (finalParams.start)
		this.props.dispatch(advancedQueryPath(finalParams));
	}

	changeDirection = () => {
		const { directionComType } = this.state;
		if (directionComType === 'all') {
			this.setState({directionComType: 'in'})
		} else if (directionComType === 'in') {
			this.setState({directionComType: 'out'})
		} else if (directionComType === 'out') {
			this.setState({directionComType: 'all'})
		}
	}
	render() {
		const { directionComType, labels, propertyKeys, relationTypes } = this.state;
		let directionCom;
		if (directionComType === 'all') {
			directionCom = <i style={{color: 'red', fontSize: 20, fontWeight: 'bold'}} className="icon iconfont icon-Thesorting"></i>
		} else if (directionComType === 'in') {
			directionCom = <Icon style={{color: 'red', fontSize: 20, fontWeight: 'bold', position: 'relative',top: 7}} type="arrow-up" />
		} else if (directionComType === 'out') {
			directionCom = <Icon style={{color: 'red', fontSize: 20, fontWeight: 'bold', position: 'relative',top: 7}} type="arrow-down" />
		}
		const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 }
    };
		return <div className="search-bar" ref="searchBar" >
			<Collapse accordion defaultActiveKey={["active"]}>
				<Panel header="详情" key="active">
		      <Form>
		      	<FormItem {...formItemLayout} label="节点总数" style={{fontSize: 12, marginBottom: 10}} >
		        	<label>{this.props.nodesCount}</label>
		        </FormItem>
		        <FormItem {...formItemLayout} label="关系总数" style={{fontSize: 12, marginBottom: 10}} >
		        	<label>{this.props.relationshipsCount}</label>
		        </FormItem>
		      </Form>
		    </Panel>
		    <Panel header="节点模糊查询" key="1">
		      <Input ref="searchValue"/>
		      <Row style={{marginTop: 7, textAlign: 'right'}}>
		      	<Button onClick={this.search}>查询</Button>
		      </Row>
		    </Panel>
		    <Panel header="节点高级查询" key="2">
		    	<AdvancedQuery searchDetailNode={this.searchDetailNode} labels={labels} propertyKeys={propertyKeys}/>
		    </Panel>
		    <Panel header="关系模糊查询" key="3">
		    	<Input ref="relationSearch"/>
		      <Row style={{marginTop: 7, textAlign: 'right'}}>
		      	<Button onClick={this.searchRelations}>查询</Button>
		      </Row>
		    </Panel>
		    <Panel header="关系高级查询" key="4">
		    	<AdvancedRelationQuery advancedQueryRelationships={this.advancedQueryRelationships} labels={labels} propertyKeys={propertyKeys} relationTypes={relationTypes}/>
		    </Panel>
		    <Panel header="节点间路径模糊查询" key="5">
		    	<Row>
		    		<Col span={4} style={{textAlign: 'center', position: 'relative', top: 17, color: '#ea0d0d'}}>{directionCom}</Col>
		    		<Col span={16}>
		    			<Row style={{marginTop: 7}}>
				    		<Input ref="start" placeholder="start"/>
				    	</Row>
				      <Row style={{marginTop: 7}}>
				    		<Input ref="destination" placeholder="destination"/>
				    	</Row>
		    		</Col>
		    		<Col span={4} style={{textAlign: 'center'}}><Icon style={{fontSize: 20, position: 'relative', top: 28}} type="retweet" onClick={this.changeDirection.bind(null, 'path')}/></Col>
		    	</Row>
		    	<Row style={{marginTop: 7}}>
		    		<Col offset={4} span={16}>
		    			<InputNumber style={{width: '100%'}} value={this.state.minLength} placeholder="minLength" onChange={this.handleChange.bind(null, 'minLength')}/>
		    		</Col>
		    	</Row>
		    	<Row style={{marginTop: 7}}>
		    		<Col offset={4} span={16}>
		    			<InputNumber style={{width: '100%'}} value={this.state.maxLength} placeholder="maxLength" onChange={this.handleChange.bind(null, 'maxLength')}/>
		    		</Col>
		    	</Row>
		    	<Row style={{marginTop: 7, textAlign: 'center'}}>
		      	<Button type="primary" onClick={this.getPaths}>查询</Button>
		      </Row>
		    </Panel>
		    <Panel header="节点间路径高级查询" key="6">
		    	<Row>
		    		<Col span={4} style={{textAlign: 'center', position: 'relative', top: 17, color: '#ea0d0d'}}>{directionCom}</Col>
		    		<Col span={16}>
		    			<Row style={{marginTop: 7}}>
				    		<Input ref="start" placeholder="start"/>
				    	</Row>
				      <Row style={{marginTop: 7}}>
				    		<Input ref="destination" placeholder="destination"/>
				    	</Row>
		    		</Col>
		    		<Col span={4} style={{textAlign: 'center'}}><Icon style={{fontSize: 20, position: 'relative', top: 28}} type="retweet" onClick={this.changeDirection.bind(null, 'path')}/></Col>
		    	</Row>
		    	<Row style={{marginTop: 7}}>
		    		<Col offset={4} span={16}>
		    			<InputNumber style={{width: '100%'}} min={0} max={1} value={this.state.minLength} placeholder="minLength" onChange={this.handleChange.bind(null, 'minLength')}/>
		    		</Col>
		    	</Row>
		    	<Row style={{marginTop: 7}}>
		    		<Col offset={4} span={16}>
		    			<InputNumber style={{width: '100%'}} min={1} max={5} value={this.state.maxLength} placeholder="maxLength" onChange={this.handleChange.bind(null, 'maxLength')}/>
		    		</Col>
		    	</Row>
		    	<Row style={{marginTop: 7, textAlign: 'center'}}>
		      	<Button type="primary" onClick={this.advancedQueryPath}>查询</Button>
		      </Row>
		    </Panel>
		    <Panel header="持卡人基于资金流向的关联关系" key="7">
		      <Button onClick={this.demo1.bind(this)}>查询</Button>
		    </Panel>
		    <Panel header="银行资金流向" key="8">
		      <Button onClick={this.demo2}>查询</Button>
		    </Panel>
		    <Panel header="根据节点ID查询指定方向的关系" key="9">
		    	<Row>
		    		<Col span={4} style={{textAlign: 'center', position: 'relative', top: 17, color: '#ea0d0d'}}>{directionCom}</Col>
		    		<Col span={16}>
		    			<Row style={{marginTop: 7}}>
				    		<Input ref="startNodeId" placeholder="startNode"/>
				    	</Row>
				      <Row style={{marginTop: 7, color: '#ccc'}}>
				    		<label style={{paddingLeft: 7}}>endNode</label>
				    	</Row>
		    		</Col>
		    		<Col span={4} style={{textAlign: 'center'}}><Icon style={{fontSize: 20, position: 'relative', top: 28}} type="retweet" onClick={this.changeDirection.bind(null, 'relation')}/></Col>
		    	</Row>
		    	<Row style={{marginTop: 7, textAlign: 'center'}}>
		      	<Button type="primary" onClick={this.getDirectedRelationByNodeId}>查询</Button>
		      </Row>
		    </Panel>
		  </Collapse>
		</div>
	}
}

function mapState2Props(state) {
	let { graphData: { nodesCount, relationshipsCount } } = state;
	return { nodesCount, relationshipsCount };
}

SearchBar = connect(mapState2Props)(SearchBar);

export default SearchBar;